import Vue from 'vue';
import VueRouter from 'vue-router';
import { Toast } from 'vant';
import routes from './routes';
import authService from '@/services/user/auth';

Vue.use(VueRouter);

// 路由配置
const router = new VueRouter({
  base: __dirname,
  routes: routes,
  caseSensitive: true
});

router.beforeEach((to, from, next) => {
  Toast.loading({
    mask: true,
    message: '加载中...',
    forbidClick: true,
    duration: 0
  });

  authService.getToken().then((token) => {
    if(token === null) {
      if(['homeIndex', 'noticeIndex', 'userLogin', 'userCreate', 'userForgetPassword'].indexOf(to.name) !== -1) {
        next();
      } else if(to.name === 'userLogin') {
        next();
      } else if(from.name === 'userLogin') {
        Toast.clear();
      } else {
        next({name: 'userLogin', replace: true});
      }
    } else {
      if(to.name === 'userLogin') {
        next({name: 'homeIndex'});
      } else {
        next();
      }
    }
  });
});

router.afterEach(() => {
  Toast.clear();
  window.scrollTo(0, 0);
});

export default router;
